package com.admin.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import org.hibernate.Session;

import tool.ClientTool;
import tool.HtmlTool;
import tool.encrypt.*;
import tool.JsonTool;
import tool.TimeTool;

import com.admin.bean.ActvOrDaka;
import com.base.bean.*;
import com.base.dao.ActivityDao;
import com.base.dao._BaseDao;
import com.base.domain.*;
import com.base.service.*;
import com.opensymphony.xwork2.ActionContext;

/**Extjs后台 汇发系
 * GPS打卡以及行动的审核
 * @author chz
 *
 */
public class GpsCheckAction2 extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private List<ActvtDetail> actvtDetailList;
	private List<DakaDetail> dakaDetailList;
	private List<ActvOrDaka> dataList;
	private Integer resultState;
	private TCheck tCheck;
	
	
	
	private Integer id;	//行动或打卡记录id
	private Integer type;		//0：查询当日记录   1：审核后再查询当日记录 
	private Integer checked;	//审核结果    0 默认   1：有效    21：无效I（不清楚  ） 22：无效II（不规范  ）23：无效（重复或作废） 3：不确定   4：系统故障
	private String checkmemo;
	
	
	
	private String date ;	//查询日期(-为分割线)
	private String jsonData;
	private String provinceId;
	private String company;
	
	//辅助类
	private GpsCheckService gcs;  //can get TCheckDao
	private DakaService dks;
	private ActivityService as;
	private UserService us;
	
	static String[] actvType = {"", "空白市场开发", "二级渠道开发", "新客户拜访", "老客户拜访", "商务谈判", "交机", "备注其他", "客户催款","电话拜访","小挖开发","电话催收"};
	
	public GpsCheckAction2() {
		// TODO Auto-generated constructor stub
		gcs = GpsCheckService.getInstance();
		dks=DakaService.getInstance();
		as=ActivityService.getInstance();	
		us=UserService.getInstance();
	}

//	//根据id以及type 获取审核的结果(id type分别对应entityId entityType)
//	public String getCheck(){
//		this.id=(this.id==null?0:this.id);
//		this.type=(this.type==null?0:this.type);	//1:打卡  2：行动
//		try{
//		this.tCheck=gcs.gettCheckDao().findByHql("from TCheck t where t.entityId="+this.id+" and t.entityType="+this.type).get(0);
//		}catch(Exception e){
//			this.tCheck=null;
//		}
//		return SUCCESS;
//	}
	
//	private TCheck getCheck(int id,int type){
//		return gcs.gettCheckDao().findByHql("from TCheck t where t.entityId="+this.id+" and t.entityType="+this.type).get(0);
//	}

	public String check(){
		this.resultState=0;
		this.tip="";
		this.checked=(this.checked==null?0:this.checked);
		this.id=(this.id==null?0:this.id);
		this.type=(this.type==null?0:this.type);
		this.checkmemo=(this.checkmemo==null?"":this.checkmemo);
		
//		System.out.println(this.memo);
		
		if(type==1)
			System.out.println("########");
		System.out.println(tip+"-"+checked+"-"+id+"-"+type);
		
		if(this.id==0){
			this.tip="没有选择任何记录";
			return SUCCESS;
		}
		
		else if(this.type==0){
			this.tip="无法判定类型";
			return SUCCESS;
		}
		
		else if(this.checked==0){
			this.tip="未进行判定";
			return SUCCESS;
		}
		
//		TCheck tc=new TCheck();
//		tc.setChecker(1);
//		tc.setCheckTime(TimeTool.getCurrentTime());
//		tc.setResult(this.checked);
//		tc.setEntityType(this.type);
		
		try{
		if(this.type==1 && this.checked!=0){	//打卡判定
			
			UserDaka ud=dks.getDkDao().findByHql("from UserDaka ud where ud.id="+this.id).get(0);
			
			ud.setChecked(this.checked);
			ud.setCheckmemo(this.checkmemo);
			dks.getDkDao().merge(ud);
			this.tip="审核打卡成功";
			this.resultState=1;
		}else if(this.type==2 && this.checked!=0){		//行动判定
			Activity acvt=as.getActvtDao().findByHql("from Activity a where a.aid="+this.id).get(0);
			
			
			acvt.setChecked(this.checked);
			acvt.setCheckmemo(this.checkmemo);
			as.getActvtDao().merge(acvt);
			
			this.tip="审核行动成功";
			this.resultState=1;
		}
		
		
		}catch(Exception e){
			this.tip="审核时出现异常";
			this.resultState=-1;
			e.printStackTrace();
			return SUCCESS;
		}
		
		//System.out.println(tip+"-"+checked+"-"+id+"-"+type);
		
		return SUCCESS;
	}
	
	
	
	@Override
	public String execute() {
		this.tip="";	
		
		
//		test
//		org.apache.commons.dbcp.BasicDataSource test= (org.apache.commons.dbcp.BasicDataSource) _BaseDao.ac.getBean("dataSource");
//		System.out.println(test.getUrl());
		AdminUser user = (AdminUser)ActionContext.getContext().getSession().get("user");
		if(user==null)
			return LOGIN;
		
		this.provinceId=user.getProvince();
		this.company = user.getCompany();
		
		this.provinceId=(this.provinceId==null?"":this.provinceId);
		this.company=(this.company==null?"":this.company);
		
		
		try{
		this.date=(this.date==null || this.date.equals("")?TimeTool.getNowTime().substring(0, 10):this.date);
		String[] arrDate=this.date.split("-");
		
		this.dataList=new ArrayList<ActvOrDaka>();
		//获取某日打卡以及考勤记录
		if(this.provinceId.equals("")){
			this.dakaDetailList=convertByDakaList(getDkList(new Integer(arrDate[0]), new Integer(arrDate[1]), new Integer(arrDate[2])));
		}else
			this.dakaDetailList=convertByDakaList(getDkList(this.company,this.provinceId,new Integer(arrDate[0]), new Integer(arrDate[1]), new Integer(arrDate[2])));
		
		if(this.dakaDetailList!=null){
			for(DakaDetail dd:this.dakaDetailList){
				ActvOrDaka data=new ActvOrDaka();
				data.setId(dd.getUserDaka().getId());
				
				Integer _checked=dd.getUserDaka().getChecked();
				_checked=(_checked==null?0:_checked);
				data.setState(_checked);
				
				data.setType(1);
				data.setName(dd.getUser().getTruename());
				data.setDep(dd.getUser().getCompany());
				data.setProvince(dd.getUser().getProvince());
				data.setCity(dd.getUser().getCity());
				data.setAddress(dd.getUserDaka().getAddName());
				data.setTime(dd.getUserDaka().getCreated());
				data.setPhoto(dd.getUserDaka().getPhotoName());
				data.setPath(dd.getUserDaka().getPath());
				if(dd.getUserDaka().getCheckmemo()!=null)
					data.setCheckmemo(dd.getUserDaka().getCheckmemo());
				else
					data.setCheckmemo("");

				dataList.add(data);
				
				
			}
		}
		
		if(this.provinceId.equals(""))
			this.actvtDetailList=this.convertByActvtList(this.getXdList(new Integer(arrDate[0]), new Integer(arrDate[1]), new Integer(arrDate[2])));
		else
			this.actvtDetailList=this.convertByActvtList(this.getXdList(this.company,this.provinceId,new Integer(arrDate[0]), new Integer(arrDate[1]), new Integer(arrDate[2])));
		if(this.actvtDetailList!=null){
			for(ActvtDetail ad:this.actvtDetailList){
				ActvOrDaka data=new ActvOrDaka();
				data.setId(ad.getActivity().getAid());
				
				Integer _checked=ad.getActivity().getChecked();
				_checked=(_checked==null?0:_checked);
				data.setState(_checked);
				
				data.setType(2);
				data.setName(ad.getUser().getTruename());
				data.setDep(ad.getUser().getCompany());
				data.setProvince(ad.getUser().getProvince());
				data.setCity(ad.getUser().getCity());
				data.setAddress(ad.getActivity().getAddress());
				data.setPhoto(ad.getActivity().getPhotoName());
				data.setTime(ad.getActivity().getCreated());
				data.setPath(ad.getActivity().getPath());
				data.setActvType(ad.getActivity().getType());	//行动类型
				
				
//				data.setClientCode("CN_"+new Integer(ad.getActivity().getCid()*2+3).toString());
				data.setClientCode(IdentifyTool.enCodeCid(ad.getActivity().getCid()));
				data.setClientName(ClientService.getInstance().getName(ad.getActivity().getCid()));

				
				Integer it=ad.getActivity().getType();
				it=(it==null?0:it);
				String content=ad.getActivity().getContent();
				content=(content==null?"":content);	
				String _type=this.actvType[it];
				data.setMemo("[行动类型]"+_type+"|[描述]"+content);
				
				if(ad.getActivity().getCheckmemo()!=null)
					data.setCheckmemo(ad.getActivity().getCheckmemo());
				else
					data.setCheckmemo("");
				
				dataList.add(data);
				
			}
			
		}
		
		this.jsonData=JsonTool.obj2json(dataList);
		
		}catch(Exception e){
			this.tip="获取记录失败(code=001)";
			e.printStackTrace();
			return ERROR;
		}

//		System.out.println(this.jsonData);

		return SUCCESS;
		

	}

//	//按省获取某日打卡的数据 使用子查询
//	private List<UserDaka> getDkList(String provinceId,int year,int month,int date){
//		Timestamp begin=TimeTool.getTimeBeginOrEnd(year, month, date, false);
//		Timestamp end=TimeTool.getTimeBeginOrEnd(year, month, date, true);
//		
//		String hql="from UserDaka ud where ud.created>'"+begin+"' and ud.created<'"+end+"'" 
//				+ " and ud.uid in (select u.uid from User u where u.provinceId='"+provinceId+"'  order by ud.uid)";
//		
//		List<UserDaka> uds=	dks.getDkDao().findByHql(hql);
//		return uds;
//	}
	
	//按省获取某日打卡的数据 使用子查询
		private List<UserDaka> getDkList(String company,String provinceId,int year,int month,int date){
			this.company=(this.company==null?"":this.company);
			Timestamp begin=TimeTool.getTimeBeginOrEnd(year, month, date, false);
			Timestamp end=TimeTool.getTimeBeginOrEnd(year, month, date, true);
			String hql="";
			if(company.equals(""))		
				 hql="from UserDaka ud where ud.created>'"+begin+"' and ud.created<'"+end+"'" 
					+ " and ud.uid in (select u.uid from User u where u.provinceId='"+provinceId+"'  order by ud.uid)";
			else if(company.equals("d"))	// 恒安是不分省份的
				 hql="from UserDaka ud where ud.created>'"+begin+"' and ud.created<'"+end+"'" 
						+ " and ud.uid in (select u.uid from User u where u.company= 'd'  order by ud.uid)";
			else
				hql="from UserDaka ud where ud.created>'"+begin+"' and ud.created<'"+end+"'" 
						+ " and ud.uid in (select u.uid from User u where (u.company= '"+company+"' or u.company2='"+company+"' )and u.provinceId='"+provinceId+"'  order by ud.uid)";
			List<UserDaka> uds=	dks.getDkDao().findByHql(hql);
			return uds;
		}
		
		
		
	
	//获取某日打卡的数据
	private List<UserDaka> getDkList(int year,int month,int date){
		Timestamp begin=TimeTool.getTimeBeginOrEnd(year, month, date, false);
		Timestamp end=TimeTool.getTimeBeginOrEnd(year, month, date, true);
		String hql="from UserDaka ud where ud.created>'"+begin+"' and ud.created<'"+end+"' order by ud.uid";	
		List<UserDaka> uds=	dks.getDkDao().findByHql(hql);
		return uds;
	}
	
	
//	//获取某日行动的数据 按省获取 子查询
//		private List<Activity> getXdList(String provinceId,int year,int month,int date){
//			Timestamp begin=TimeTool.getTimeBeginOrEnd(year, month, date, false);
//			Timestamp end=TimeTool.getTimeBeginOrEnd(year, month, date, true);
//			String hql="from Activity a where a.created>'"+begin+"' and a.created<'"+end+"'"	
//					+ "and a.creator in (select u.uid from User u where u.provinceId='"+provinceId+"')"
//					+ " order by a.creator";
//			
//			
//			List<Activity> acvts=	as.getActvtDao().findByHql(hql);
//			return acvts;
//		}
		
		//获取某日行动的数据 按省获取 子查询
				private List<Activity> getXdList(String company,String provinceId,int year,int month,int date){
					this.company=(this.company==null?"":this.company);
					
					Timestamp begin=TimeTool.getTimeBeginOrEnd(year, month, date, false);
					Timestamp end=TimeTool.getTimeBeginOrEnd(year, month, date, true);
					String hql="";
					if(company.equals(""))
						hql="from Activity a where a.created>'"+begin+"' and a.created<'"+end+"'"	
							+ "and a.creator in (select u.uid from User u where u.provinceId='"+provinceId+"')"
							+ " order by a.creator";
					else
						hql="from Activity a where a.created>'"+begin+"' and a.created<'"+end+"'"	
								+ "and a.creator in (select u.uid from User u where (u.company='"+company+"' or u.company2='"+company+"' ) and u.provinceId='"+provinceId+"')"
								+ " order by a.creator";
					
					List<Activity> acvts=	as.getActvtDao().findByHql(hql);
					return acvts;
				}	
		
	
	//获取某日行动的数据
	private List<Activity> getXdList(int year,int month,int date){
		Timestamp begin=TimeTool.getTimeBeginOrEnd(year, month, date, false);
		Timestamp end=TimeTool.getTimeBeginOrEnd(year, month, date, true);
		String hql="from Activity a where a.created>'"+begin+"' and a.created<'"+end+"' order by a.creator";	
		List<Activity> acvts=	as.getActvtDao().findByHql(hql);
		return acvts;
	}
	
	//行动转化为ActvtDetial
	private List<ActvtDetail> convertByActvtList(List<Activity> acvts){
		List<ActvtDetail> list=new ArrayList<ActvtDetail>();
		try{
		for(Activity a:acvts){
			ActvtDetail ad=new ActvtDetail();
			ad.setActivity(a);
			try{
			ad.setUser(us.getUserDao().findByHql("from User u where u.uid="+a.getCreator()).get(0));
			list.add(ad);
			}catch(Exception e){	//未找到用户则跳过
				continue;
			}
		}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return list;
	}
	
	//打卡转化为DakaDetail
	private List<DakaDetail> convertByDakaList(List<UserDaka> dks){
		List<DakaDetail> list=new ArrayList<DakaDetail>();
		try{
		for(UserDaka dk:dks){
			DakaDetail dd=new DakaDetail();
			dd.setUserDaka(dk);
			try{
			dd.setUser(us.getUserDao().findByHql("from User u where u.uid="+dk.getUid()).get(0));
			list.add(dd);
			}catch(Exception e){	//未找到用户则跳过
				continue;
			}
		}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return list;
	}
	
	
	

	
	public static void main(String[] args){
	
		GpsCheckAction2 a=new GpsCheckAction2();
//		List<UserDaka> list = a.getDkList("620000", 2016, 4, 1);
//		for(UserDaka ud:list){
//			System.out.println(ud.getAddName());
//		}
		
		List<Activity> list2 = a.getXdList("a","620000", 2016, 4, 1);
		for(Activity act :list2){
			System.out.println(act.getAddress()+"|"+act.getType());
		}
		
		
	}
	

	


	public List<ActvtDetail> getActvtDetailList() {
		return actvtDetailList;
	}


	public void setActvtDetailList(List<ActvtDetail> actvtDetailList) {
		this.actvtDetailList = actvtDetailList;
	}


	public List<DakaDetail> getDakaDetailList() {
		return dakaDetailList;
	}


	public void setDakaDetailList(List<DakaDetail> dakaDetailList) {
		this.dakaDetailList = dakaDetailList;
	}


	public List<ActvOrDaka> getDataList() {
		return dataList;
	}


	public void setDataList(List<ActvOrDaka> dataList) {
		this.dataList = dataList;
	}


	public Integer getId() {
		return id;
	}


	public void setId(Integer id) {
		this.id = id;
	}


	public Integer getType() {
		return type;
	}


	public void setType(Integer type) {
		this.type = type;
	}


	public Integer getChecked() {
		return checked;
	}


	public void setChecked(Integer checked) {
		this.checked = checked;
	}

	public String getCheckmemo() {
		return checkmemo;
	}

	public void setCheckmemo(String checkmemo) {
		this.checkmemo = checkmemo;
	}

	public String getDate() {
		return date;
	}


	public void setDate(String date) {
		this.date = date;
	}


	public String getJsonData() {
		return jsonData;
	}


	public void setJsonData(String jsonData) {
		this.jsonData = jsonData;
	}


	public Integer getResultState() {
		return resultState;
	}


	public void setResultState(Integer resultState) {
		this.resultState = resultState;
	}

	public TCheck gettCheck() {
		return tCheck;
	}

	public void settCheck(TCheck tCheck) {
		this.tCheck = tCheck;
	}

	public String getProvinceId() {
		return provinceId;
	}

	public void setProvinceId(String provinceId) {
		this.provinceId = provinceId;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}


	

	


	


	


	



	

	




}
